package top.byfree.jbyan.saber.common

import org.ktorm.dsl.asc
import org.ktorm.dsl.desc
import org.ktorm.expression.OrderByExpression
import org.ktorm.schema.Table
import top.byfree.jbyan.saber.exception.SaberServiceException
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*


/**
 * kt扩展工具
 *
 * @author jbyan
 * @since 25/3/2024
 */

fun String.isValidEmail(): Boolean {
    val regex = Regex("""^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$""")
    return regex.matches(this)
}



fun Table<*>.coverOrderBy(orderBy: MutableList<OrderDto>?): MutableList<OrderByExpression>? {
    return orderBy?.let {
        val columnMap = this.columns.associateBy { cl ->
            cl.name
        }
        it.map { st ->
            val column = columnMap[st.col]
            column ?: throw SaberServiceException("排序字段未处于待排序列表中")
            st.type?.let { bo ->
                if (bo) column.asc() else column.desc()
            } ?: column.asc()
        }.toMutableList()
    }
}

fun LocalDateTime.formatter(pattern: String = "yyyy-MM-dd HH:mm:ss"): String {
    val ofPattern = DateTimeFormatter.ofPattern(pattern)
    return ofPattern.format(this)
}



fun createCode(n: Int): String {
    val sb = StringBuilder()
    val rand = Random()
    var num = 0
    (0 until n).forEach { i ->
        num = rand.nextInt(9)
        sb.append(num)
    }
    return sb.toString()
}